import React, { useMemo, useState } from 'react';
import { 
  Table, 
  Tag, 
  Typography, 
  Space, 
  Button,
  Tooltip,
  Modal
} from 'antd';
import RuleDetailModal from './RuleDetailModal';
import { 
  EyeOutlined,
  BulbOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import './ProblemTable.css';

const { Text, Paragraph } = Typography;

interface Problem {
  id: string;
  lineNumber: number;
  columnNumber: number;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  category: string;
  description: string;
  suggestion: string;
  ruleName?: string;
  originalCode?: string;
  suggestedCode?: string;
  sqlFragment?: string; // 新增SQL片段字段
  
  // AI增强验证字段 (v4.2新增)
  ruleAnalysisConfirmed?: boolean;      // 规则分析是否被AI确认
  aiIssueDescription?: string;          // AI分析的问题描述
  aiConfidenceScore?: number;           // AI分析置信度
  optimizedSql?: string;                // AI优化后的完整SQL语句
  optimizationExplanation?: string;     // AI优化说明
  analysisEngine?: string;              // 分析引擎
  aiOptimized?: boolean;                // 是否经过AI优化
}

interface ProblemGroup {
  key: string;
  title: string;
  icon: React.ReactNode;
  count: number;
  items: Problem[];
  color: string;
}

interface ProblemTableProps {
  problems: ProblemGroup[];
  selectedIssueId?: string | null;
  onIssueClick?: (issue: Problem) => void;
  height?: number;
}

const ProblemTable: React.FC<ProblemTableProps> = ({
  problems,
  selectedIssueId,
  onIssueClick,
  height = 400
}) => {
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedProblem, setSelectedProblem] = useState<Problem | null>(null);
  
  // 规则详情模态框状态
  const [ruleDetailVisible, setRuleDetailVisible] = useState(false);
  const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null);

  // 将分组问题展平为表格数据
  const tableData = useMemo(() => {
    const result: (Problem & { groupKey: string; groupTitle: string; groupColor: string })[] = [];
    
    problems.forEach(group => {
      // 去除重复项（基于id去重）
      const uniqueItems = group.items.filter((item, index, arr) => 
        arr.findIndex(i => i.id === item.id) === index
      );

      uniqueItems.forEach(item => {
        result.push({
          ...item,
          groupKey: group.key,
          groupTitle: group.title,
          groupColor: group.color
        });
      });
    });
    
    return result;
  }, [problems]);

  // 获取严重程度标签
  const getSeverityTag = (severity: string) => {
    const configs = {
      'HIGH': { color: 'error', text: '高危' },
      'MEDIUM': { color: 'warning', text: '中危' },
      'LOW': { color: 'processing', text: '低危' },
      'INFO': { color: 'success', text: '提示' }
    };
    const config = configs[severity as keyof typeof configs] || { color: 'default', text: severity };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 简单的SQL语法高亮函数
  const highlightSql = (sql: string) => {
    const keywords = ['SELECT', 'FROM', 'WHERE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'OUTER', 'ON', 'AND', 'OR', 'ORDER', 'BY', 'GROUP', 'HAVING', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER', 'TABLE', 'INDEX', 'VIEW', 'INTO', 'VALUES', 'SET', 'DISTINCT', 'AS', 'ASC', 'DESC', 'LIMIT', 'OFFSET', 'UNION', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'IF', 'NULL', 'NOT', 'IS', 'IN', 'LIKE', 'BETWEEN', 'EXISTS', 'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'ROWNUM'];
    
    let highlighted = sql;
    
    // 高亮关键字
    keywords.forEach(keyword => {
      const regex = new RegExp(`\\b${keyword}\\b`, 'gi');
      highlighted = highlighted.replace(regex, `<span class="sql-keyword">${keyword.toUpperCase()}</span>`);
    });
    
    // 高亮字符串
    highlighted = highlighted.replace(/'([^']*)'/g, '<span class="sql-string">\'$1\'</span>');
    highlighted = highlighted.replace(/"([^"]*)"/g, '<span class="sql-string">"$1"</span>');
    
    // 高亮数字
    highlighted = highlighted.replace(/\b\d+\b/g, '<span class="sql-number">$&</span>');
    
    // 高亮注释
    highlighted = highlighted.replace(/--(.*)$/gm, '<span class="sql-comment">--$1</span>');
    highlighted = highlighted.replace(/\/\*[\s\S]*?\*\//g, '<span class="sql-comment">$&</span>');
    
    return highlighted;
  };
  const handleViewDetail = (problem: Problem) => {
    setSelectedProblem(problem);
    setDetailModalVisible(true);
  };

  // 处理行点击
  const handleRowClick = (problem: Problem) => {
    onIssueClick?.(problem);
  };

  // 处理规则名称点击
  const handleRuleNameClick = (ruleId: string | undefined, event: React.MouseEvent) => {
    event.stopPropagation(); // 阻止行点击事件
    if (ruleId && ruleId !== 'AI001' && !ruleId.startsWith('AI')) {
      setSelectedRuleId(ruleId);
      setRuleDetailVisible(true);
    }
  };

  // 关闭规则详情模态框
  const handleRuleDetailClose = () => {
    setRuleDetailVisible(false);
    setSelectedRuleId(null);
  };

  // 表格列定义
  const columns: ColumnsType<Problem & { groupKey: string; groupTitle: string; groupColor: string }> = [
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      width: 95,
      render: (severity: string) => getSeverityTag(severity),
      sorter: (a, b) => {
        const order = { HIGH: 4, MEDIUM: 3, LOW: 2, INFO: 1 };
        return (order[a.severity as keyof typeof order] || 0) - (order[b.severity as keyof typeof order] || 0);
      },
      defaultSortOrder: 'descend'
    },
    {
      title: '规则ID',
      dataIndex: 'ruleName',
      key: 'ruleName',
      width: 130,
      render: (ruleName: string, record) => {
        // AI验证状态
        const isAiVerified = record.ruleAnalysisConfirmed !== undefined;
        const isConfirmedByAI = record.ruleAnalysisConfirmed === true;
        
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
            {/* AI验证状态标识 */}
            {isAiVerified && (
              <Tag 
                color={isConfirmedByAI ? 'red' : 'cyan'} 
                style={{ fontSize: '9px', padding: '0 4px', margin: 0 }}
              >
                {isConfirmedByAI ? 'AI确认' : 'AI质疑'}
              </Tag>
            )}
            
            {/* 规则ID或名称 */}
            {ruleName && ruleName !== 'AI001' && !ruleName.startsWith('AI') ? (
              <Button
                type="link"
                size="small"
                onClick={(e) => handleRuleNameClick(ruleName, e)}
                style={{ padding: 0, fontFamily: 'monospace', fontSize: '12px' }}
              >
                {ruleName}
              </Button>
            ) : ruleName ? (
              <Text type="secondary" style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                {ruleName}
              </Text>
            ) : (
              <Text type="secondary">-</Text>
            )}
          </div>
        );
      }
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 130,
      ellipsis: false, // 禁用省略号，避免覆盖
      render: (category: string) => (
        <Tag 
          color="blue" 
          style={{ 
            margin: 0,
            maxWidth: '100%',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            display: 'block'
          }}
        >
          {category}
        </Tag>
      ),
      filters: [
        { text: '语法', value: 'SYNTAX' },
        { text: '函数', value: 'FUNCTION' },
        { text: '数据类型', value: 'DATATYPE' },
        { text: '性能', value: 'PERFORMANCE' }
      ],
      onFilter: (value, record) => record.category === value
    },
    {
      title: '问题描述',
      dataIndex: 'description',
      key: 'description',
      width: 300,
      ellipsis: {
        showTitle: false
      },
      render: (description: string) => (
        <Tooltip title={description} placement="topLeft">
          <Text style={{ color: '#262626', fontSize: '13px' }}>
            {description}
          </Text>
        </Tooltip>
      )
    },
    {
      title: 'SQL片段',
      dataIndex: 'sqlFragment',
      key: 'sqlFragment',
      width: 240,
      ellipsis: {
        showTitle: false
      },
      render: (sqlFragment: string, record) => {
        // 优先使用sqlFragment，如果没有则使用originalCode
        const displayCode = sqlFragment || record.originalCode;
        
        return displayCode ? (
          <Tooltip title={displayCode} placement="topLeft">
            <div className="sql-fragment-container">
              <div 
                className="sql-fragment-text"
                dangerouslySetInnerHTML={{ 
                  __html: highlightSql(displayCode) 
                }}
              />
              {displayCode.length > 50 && (
                <div className="sql-fragment-ellipsis">
                  ...
                </div>
              )}
            </div>
          </Tooltip>
        ) : (
          <Text type="secondary" style={{ fontSize: '12px' }}>无代码片段</Text>
        );
      }
    },
    {
      title: '修改建议',
      dataIndex: 'suggestion',
      key: 'suggestion',
      width: 280,
      ellipsis: {
        showTitle: false
      },
      render: (suggestion: string) => (
        suggestion ? (
          <Tooltip title={suggestion} placement="topLeft">
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px' }}>
              <BulbOutlined style={{ color: '#52c41a', marginTop: '2px', flexShrink: 0 }} />
              <Text style={{ 
                color: '#52c41a', 
                fontSize: '12px',
                display: '-webkit-box',
                WebkitLineClamp: 2,
                WebkitBoxOrient: 'vertical',
                overflow: 'hidden',
                lineHeight: '1.4'
              }}>
                {suggestion}
              </Text>
            </div>
          </Tooltip>
        ) : (
          <Text type="secondary">-</Text>
        )
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 90,
      fixed: 'right', // 固定操作列在右侧
      render: (_, record) => (
        <Tooltip title="查看详情">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              handleViewDetail(record);
            }}
          />
        </Tooltip>
      )
    }
  ];

  return (
    <div className="problem-table">
      <div className="problem-table-header">
        <Text strong>共 {tableData.length} 个问题</Text>
      </div>
      
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        size="small"
        scroll={{ 
          y: height - 120,
          x: 1265 // 总列宽，确保水平滚动
        }}
        pagination={{
          pageSize: 50,
          showSizeChanger: true,
          pageSizeOptions: ['25', '50', '100', '200'],
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
          size: 'default'
        }}
        rowClassName={(record) => 
          selectedIssueId === record.id ? 'problem-row-selected' : 'problem-row'
        }
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
          style: { cursor: 'pointer' }
        })}
      />

      {/* 问题详情弹窗 */}
      <Modal
        title={
          <Space>
            <span>问题详情</span>
            {selectedProblem && getSeverityTag(selectedProblem.severity)}
          </Space>
        }
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedProblem && (
          <div className="problem-detail">
            <div className="detail-section">
              <Text strong>位置：</Text>
              <Text>第 {selectedProblem.lineNumber} 行，第 {selectedProblem.columnNumber} 列</Text>
            </div>
            
            {/* AI验证状态详细信息 */}
            {selectedProblem.ruleAnalysisConfirmed !== undefined && (
              <div className="detail-section">
                <Text strong>AI验证结果：</Text>
                <div style={{ marginTop: 8 }}>
                  <Tag 
                    color={selectedProblem.ruleAnalysisConfirmed ? 'red' : 'cyan'}
                    style={{ fontSize: '12px', marginBottom: 8 }}
                  >
                    {selectedProblem.ruleAnalysisConfirmed ? 'AI确认此问题确实存在' : 'AI认为此问题可能不重要或误判'}
                  </Tag>
                  {selectedProblem.aiConfidenceScore && (
                    <Tag color="blue" style={{ marginLeft: 8 }}>
                      AI置信度: {Math.round(selectedProblem.aiConfidenceScore * 100)}%
                    </Tag>
                  )}
                  {selectedProblem.aiIssueDescription && (
                    <div style={{ marginTop: 8, padding: '8px 12px', background: '#f6f8fa', borderRadius: '6px' }}>
                      <Text strong style={{ fontSize: '12px' }}>AI分析描述：</Text>
                      <Paragraph style={{ marginTop: 4, marginBottom: 0, fontSize: '12px' }}>
                        {selectedProblem.aiIssueDescription}
                      </Paragraph>
                    </div>
                  )}
                </div>
              </div>
            )}
            
            <div className="detail-section">
              <Text strong>分类：</Text>
              <Tag color="blue">{selectedProblem.category}</Tag>
            </div>
            
            {selectedProblem.ruleName && (
              <div className="detail-section">
                <Text strong>问题名称：</Text>
                {selectedProblem.ruleName !== 'AI001' && !selectedProblem.ruleName.startsWith('AI') ? (
                  <Button
                    type="link"
                    size="small"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRuleNameClick(selectedProblem.ruleName, e);
                    }}
                    style={{ 
                      padding: '2px 6px',
                      fontSize: '13px',
                      fontWeight: '500',
                      background: 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)',
                      color: '#ffffff',
                      borderRadius: '6px',
                      border: 'none',
                      textDecoration: 'none',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '4px',
                      marginLeft: '8px',
                      transition: 'all 0.3s ease'
                    }}
                    className="problem-name-clickable"
                  >
                    <EyeOutlined style={{ fontSize: '11px' }} />
                    点击查看规则详情
                  </Button>
                ) : (
                  <Text style={{ marginLeft: 8, fontWeight: '500' }}>
                    {selectedProblem.ruleName}
                  </Text>
                )}
              </div>
            )}
            
            <div className="detail-section">
              <Text strong>问题描述：</Text>
              <Paragraph style={{ marginTop: 8 }}>
                {selectedProblem.description}
              </Paragraph>
            </div>
            
            {(selectedProblem.sqlFragment || selectedProblem.originalCode) && (
              <div className="detail-section">
                <Text strong>SQL片段：</Text>
                <div className="code-block">
                  <pre dangerouslySetInnerHTML={{ 
                    __html: highlightSql((selectedProblem.sqlFragment || selectedProblem.originalCode) || '') 
                  }} />
                </div>
              </div>
            )}
            
            {selectedProblem.originalCode && selectedProblem.sqlFragment && selectedProblem.originalCode !== selectedProblem.sqlFragment && (
              <div className="detail-section">
                <Text strong>完整问题代码：</Text>
                <div className="code-block">
                  <pre dangerouslySetInnerHTML={{ 
                    __html: highlightSql(selectedProblem.originalCode || '') 
                  }} />
                </div>
              </div>
            )}
            
            {selectedProblem.suggestion && (
              <div className="detail-section">
                <Text strong>修复建议：</Text>
                <div className="suggestion-block">
                  <BulbOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                  <Text>{selectedProblem.suggestion}</Text>
                </div>
              </div>
            )}
            
            {selectedProblem.suggestedCode && (
              <div className="detail-section">
                <Text strong>建议代码：</Text>
                <div className="code-block suggested">
                  <pre dangerouslySetInnerHTML={{ 
                    __html: highlightSql(selectedProblem.suggestedCode || '') 
                  }} />
                </div>
              </div>
            )}
            
            {/* AI优化后的完整SQL语句 */}
            {selectedProblem.optimizedSql && (
              <div className="detail-section">
                <Text strong>AI优化后SQL：</Text>
                <div className="code-block ai-optimized" style={{ border: '1px solid #722ed1', borderRadius: '6px' }}>
                  <pre dangerouslySetInnerHTML={{ 
                    __html: highlightSql(selectedProblem.optimizedSql || '') 
                  }} />
                </div>
              </div>
            )}
            
            {/* AI优化说明 */}
            {selectedProblem.optimizationExplanation && (
              <div className="detail-section">
                <Text strong>AI优化说明：</Text>
                <div style={{ 
                  marginTop: 8, 
                  padding: '12px', 
                  background: '#f9f0ff', 
                  borderRadius: '6px',
                  border: '1px solid #d3adf7'
                }}>
                  <Text style={{ fontSize: '13px', lineHeight: '1.6' }}>
                    {selectedProblem.optimizationExplanation}
                  </Text>
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* 规则详情模态框 */}
      <RuleDetailModal
        visible={ruleDetailVisible}
        ruleId={selectedRuleId}
        onClose={handleRuleDetailClose}
      />
    </div>
  );
};

export default ProblemTable;